package controller.ur;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import model.dao.UserDaoLocal;
import model.entity.User;
import controller.CUtil;

/**
 * Servlet implementation class SChangePasswordOut
 */
public class SChangePasswordOut extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	@EJB
	private UserDaoLocal userDao;
	
	private Logger log=Logger.getLogger(SChangePasswordOut.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SChangePasswordOut() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		request.setCharacterEncoding("UTF-8");
		
		User user=(User)request.getSession().getAttribute("user");
		String oldPassword=(String)request.getParameter("oldPassword");
		if(!oldPassword.equals(user.getPassword())){
			request.setAttribute("message", "Bad old password!");
			CUtil.redirecter(request, response, "ur/VChangePassword.jsp");
			return;
		}
		String newPassword=(String)request.getParameter("newPassword");
		user.setPassword(newPassword);
		userDao.merge(user);
		log.info("User changed password: "+user.toString());
		CUtil.lastPageRedirect(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
